package org.paradigmshift.timelapse.ui

import scala.actors.Actor
import org.paradigmshift.timelapse.stopwatch.Time
import org.paradigmshift.timelapse.stopwatch.Stopwatch
import scala.swing.Label
import org.paradigmshift.timelapse.stopwatch.Add
import scala.swing.BoxPanel
import scala.swing.Orientation
import scala.swing.Alignment
import scala.swing.Swing
import org.paradigmshift.timelapse.actor.messages.Exit

class StopwatchDisplay extends BoxPanel( Orientation.Horizontal ) with Actor {
  
  val timerLabel = new Label {
    text = "00:00:00"
    horizontalAlignment = Alignment.Center
    border = Swing.EmptyBorder( 2, 4, 2, 4 )
  }
  
  contents += new BoxPanel( Orientation.Horizontal ) {
    contents += timerLabel
    border = Swing.EtchedBorder( Swing.Lowered )
  }
  border = Swing.EmptyBorder( 0, 30, 0, 0 )
  
  start()
  
  def act(): Unit = {
    loop {
      react {
        case time : Time => {
          val elapsedHours = time.seconds / Stopwatch.SECONDS_IN_AN_HOUR
          val elapsedMinutes = time.seconds % Stopwatch.SECONDS_IN_AN_HOUR / Stopwatch.SECONDS_IN_A_MINUTE
          val elapsedSeconds = time.seconds % Stopwatch.SECONDS_IN_AN_HOUR % Stopwatch.SECONDS_IN_A_MINUTE
          
          val formattedTime = new StringBuilder( 8 )
          if ( elapsedHours < 10 ) formattedTime.append( '0' )
          formattedTime.append( elapsedHours )
          formattedTime.append( ':' )
          if ( elapsedMinutes < 10 ) formattedTime.append( '0' )
          formattedTime.append( elapsedMinutes )
          formattedTime.append( ':' )
          if ( elapsedSeconds < 10 ) formattedTime.append( '0' )
          formattedTime.append( elapsedSeconds )
          
          timerLabel.text = formattedTime.toString()
        }
        case Exit => exit
      }
    }
  }
}